<?php
namespace Wx\Controller;
use Think\Controller;
class CartController extends Controller{
    /**
     * 清空购物车
     */
    public function destroyCart(){

        $res = D('Cart')->destroyCart();
        $this->ajaxReturn($res);

    }
    /**
     * 加入购物车
     *
     */
    public  function addCart(){
        if(!session('oto_userId')){
            $this->ajaxReturn(['status'=>-17,'msg'=>'未登录']);
            return;
        }

        // $province=I('province');
        // $city=I('city');
        // $area=I('area');
        // $community=I('community');
        // if(empty($province)||empty($city)||empty($area)){
        //     $this->ajaxReturn(array('status=>-5'));
        //     return;
        // }
        // //配送范围判断
        // $goodsId=I('goodsId');

        // $shopid=M('goods')->where(array('goodsId'=>$goodsId))->getField('shopId');


        // $checkIsSendChina = M('shops_communitys')->field('communityId')->where(array('shopId'=>$shopid,'areaId1'=>0,'areaId2'=>0,'areaId3'=>0))->find();
        // if(!$checkIsSendChina){

        // if($community){
        //         $range=M('shops_communitys')->field('communityId')->where(array('shopId'=>$shopid,'communityId'=>$community))->find();
        //         if(!$range){
        //             //不在配送范围
        //             $this->ajaxReturn(array('status'=>-6,'message'=>'不在配送范围'));
        //             return;
        //         }


        // }else if($area){
        //     //区级配送范围
        //     $range=M('shops_communitys')->field('areaId3')->where(array('shopId'=>$shopid,'areaId3'=>$area))->find();
        //     if(!$range){
        //         //不在配送范围
        //         $this->ajaxReturn(array('status'=>-6,'message'=>'不在配送范围'));
        //         return;
        //     }
        // }
        // }
        //范围判断 结束

        //判断库存
        $goodsId=I('goodsId');
        $attrId=I('goodsAttrId');
        $gcount=I('gcount');//数量
        $isGroup=I('isGroup',0);
        $isSeckill=I('isSeckill',0);
        $groupId = I('groupId');//团购表id


        //如果是秒杀或者团购，一步购物清除对应商品，以最新数量为准
        if($isGroup==1||$isSeckill==1){
            $goodsKey = $goodsId."_".$attrId."_".$isSeckill."_".$isGroup;
            $shopcart = session("WST_CART")?session("WST_CART"):array();

            $map['userId']= session('oto_userId');
            $isCarExists=M('car_session')->where($map)->field('car_session,userId')->find();
            $dbCarInfo=unserialize($isCarExists['car_session']);
            $shopcart=session("WST_CART");
            $newShopcat = array();
            foreach($shopcart as $key=>$cgoods){
                if($goodsKey != $key){
                    $newShopcat[$key] = $cgoods;
                }
            }
            if($isCarExists['userId']){
                $isCarExists=M('car_session')->where($map)->save(array('car_session'=>serialize($newShopcat)));
            }else{
                $saveData['car_session']=serialize($newShopcat);
                $saveData['userId']=session('oto_userId');
                $isCarExists=M('car_session')->add($saveData);
            }
            session("WST_CART",$newShopcat);
        }


        //判断商品状态
        $stotck=M('goods')->where(array('goodsId'=>$goodsId,'goodsStatus'=>1,'goodsFlag'=>1))->find();
        if(!$stotck){
            $this->ajaxReturn(array('status'=>-9,'msg'=>'商品已经下架'));
            return;
        }

        //判断库存用
        $map['userId']= session('oto_userId');
        $isCarExists=M('car_session')->where($map)->field('car_session,userId')->find();
        $WST_CART=unserialize($isCarExists['car_session']);

        $goodsInfo = D('Wx/Cart')->getGoodsInfo((int)I("goodsId"),I("goodsAttrId"),(int)I("isSeckill",0),(int)I("isGroup",0),(int)I('groupId',0));

        $goodsAttrId = '';
        $price = 0.0;
        foreach($goodsInfo as $k=>$v){
            if(is_numeric($k)) {
                //拼接属性ID
                $goodsAttrId .= $goodsInfo[$k]['goodsAttrId'].'_';
            }
        }
        $goodsAttrId=rtrim($goodsAttrId,'_');
        //按升序排序
        $temp=explode('_', $goodsAttrId);
        asort($temp);
        $goodsAttrId=implode('_', $temp);
        //如果没有属性，默认为0
        if(empty($goodsAttrId)){
            $goodsAttrId=0;
        }
        $cartNum=$WST_CART[$goodsInfo["goodsId"]."_".$goodsAttrId."_".$isSeckill.'_'.$isGroup]["cnt"];

        if($isGroup){
            $time = time();
            $groupInfo = M('goods_group')->where(['goodsId'=>$goodsId,'shopId'=>I('shopId'),'groupStatus'=>1,'startTime'=>['lt',$time], 'endTime'=>['gt',$time]] )->find();
            //$groupInfo = M('goods_group')->where(array('goodsId'=>$goodsId,'groupStatus'=>1,'id'=>$groupId))->find();
            //echo M()->getLastSql();die;
            //团购最大数量
            //$maxGroup=M('goods_group')->where(array('goodsId'=>$goodsId,'groupStatus'=>1,'Id'=>$groupId))->getField('groupMaxCount');
            $maxGroup = $groupInfo['groupMaxCount'];
            if(!$maxGroup){
                $this->ajaxReturn(array('status'=>-7,'msg'=>'团购已结束'));
                return;
            }
            //所有人下的团购订单数
           //$sql="select count(og.goodsNums) as saleNum from oto_order_goods as og join oto_goods_group as gg on og.goodsId=gg.goodsId and gg.groupStatus=1 join oto_orders as od on od.orderId=og.orderId and od.orderType=3 where og.goodsId=$goodsId";
          // $saleNum=M()->query($sql);
            //$saleNum=$saleNum[0]['saleNum'];//总销量

            $dbGroup = D('Wx/Group');
            $startDate = date('Y-m-d H:i:s',$groupInfo['startTime']);
            $endDate   = date('Y-m-d H:i:s',$groupInfo['endTime']);
            $saleNum = $dbGroup->getOrderGroup($groupInfo['goodsId'],$startDate,$endDate,$groupInfo['id']);//总销量

           if($saleNum>=$maxGroup){
               $this->ajaxReturn(array('status'=>-8,'msg'=>'团购商品限购'.$maxGroup.'件'));
               return;
           }
          //库存
           $short=$maxGroup-$saleNum;

           //购物车中的商品已经大于库存
           if($cartNum&&$cartNum>=$short){
               $this->ajaxReturn(array('status'=>-9,'msg'=>'库存不足'));
               return;
           }

           if($gcount >$short){
               $this->ajaxReturn(array('status'=>-9,'msg'=>'团购商品限购'.$short.'件'));
               return;
           }

        }else if($isSeckill){
            $seckillMap['goodsId']=$goodsId;
            $seckillMap['seckillStatus']=1;
            $seckillMap['goodsSeckillStatus']=1;
            $time=time();
            $seckillMap['_string']="$time between seckillStartTime and seckillEndTime";
            $secKill=M('goods_seckill')->where($seckillMap)->getField('seckillMaxCount');
            if(!$secKill){
                $this->ajaxReturn(array('status'=>-10,'msg'=>'秒杀已结束'));
                return;
            }
            $secKillStock=M('goods')->where(array('goodsId'=>$goodsId))->getField('goodsStock');
            if(!$secKillStock){
                $this->ajaxReturn(array('status'=>-12,'msg'=>'秒杀商品已售罄'));
                return;
            }
            if($gcount>$secKillStock){
                $this->ajaxReturn(array('status'=>-13,'msg'=>'秒杀商品库存只剩下'.$secKillStock.'份'));
                return;
            }

            //限购，购物车中商品大于限购或者加车数量大小限购数量
            $couMap['oto_orders.orderStatus']=array('egt',0);
            $couMap['oto_orders.isPay']=array('eq',1);
            $couMap['oto_orders.orderType']=array('eq',2);
            $couMap['oto_order_goods.goodsId']=array('eq',$goodsId);
            $couMap['oto_orders.userId']=array('eq',session('oto_userId'));
            $payCount=M('order_goods')->join('oto_orders on oto_orders.orderId=oto_order_goods.orderId')->where($couMap)->sum('oto_order_goods.goodsNums');


            if($gcount+$payCount>$secKill||$cartNum+$gcount>$secKill){
                $this->ajaxReturn(array('status'=>-14,'msg'=>'限购'.$secKill.'份'));
                return;
            }
        }else{
            if($attrId){
                $attrstotck=M('goods_attributes')->where(array('goodsId'=>$goodsId,'id'=>array('in',$attrId)))->getField('attrStock');
                if($cartNum>=$attrstotck){
                    $this->ajaxReturn(array('status'=>-15,'msg'=>'库存不足'));
                    return;
                }

                if($gcount>$attrstotck){
                    $this->ajaxReturn(array('status'=>-10,'msg'=>'商品库存只剩下'.$attrstotck));
                    return;
                }
            }else{
                if($cartNum>=$stotck['goodsStock']){
                    $this->ajaxReturn(array('status'=>-15,'msg'=>'库存不足'));
                    return;
                }
                if($gcount>$stotck['goodsStock']){
                   $this->ajaxReturn(array('status'=>-10,'msg'=>'商品库存只剩下'.$stotck['goodsStock'].'份'));
                    return;
                }
            }
        }
        $m = D('Wx/Cart');
        $res = $m->addToCart();
        $this->ajaxReturn($res);
    }

    /**
     * 获取购物车商品数量
     */
    public function getCartGoodCnt(){
        $map['userId']= session('oto_userId');
        $isCarExists=M('car_session')->where($map)->field('car_session,userId')->find();
        if($isCarExists){
            $shopcart=unserialize($isCarExists['car_session']);
            $goodsCut=count($shopcart);
            if(IS_AJAX){
                if($goodsCut){
                    $this->ajaxReturn(array('goodscnt'=>$goodsCut));
                }else {
                    $this->ajaxReturn(array('goodscnt'=>0));
                }
            }else{
                return $goodsCut;
            }
        }else{
            if(IS_AJAX){
                  $this->ajaxReturn(array('goodscnt'=>0));
            }else{
                return 0;
            }
        }
    }

    /**
     * 获取商品库存
     *
     */
    public function getGoodsStock(){
        $data = array();
        $data['goodsId'] = (int)I('goodsId');
        $data['isBook'] = (int)I('isBook');
        $data['goodsAttrId'] = (int)I('goodsAttrId');
        $data['isGroup']=I('isGround',0,intval);
        $data['isSeckill']=I('isSeckill',0,intval);
        $goods = D('Wx/Cart');
        $goodsStock = $goods->getGoodsStock($data);
        echo json_encode($goodsStock);
    }

    /**
     * 修改购物车中的商品数量
     *
     */
    public function changeCartGoodsNum(){
        $m = D('Wx/Cart');
        $res = $m->changeCartGoodsnum();
        $this->ajaxReturn($res);
    }


    /**
     * 检测购物车中商品库存
     *
     */
    public function checkCartGoodsStock(){
        $m = D('Wx/Cart');
        $res = $m->checkCatGoodsStock();
        echo json_encode($res);
    }
    /**
     * 检测选中的购物车中商品库存
     *
     */
    public function checkSelectGoodsStock(){
        $m = D('Wx/Cart');
        $res = $m->checkSelectGoodsStock();
        echo json_encode($res);
    }

    /**
     * 获取购物车商品信息
     */
    public function getCartInfo(){
        $m = D('Wx/Cart');
        $res = $m->getCartInfo();
        $this->ajaxReturn($res);
    }

    public  function cart(){
        $this->display();
    }

}